package cn.com.easy.permission.service.system.userindex;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.easy.permission.dao.ResourceDao;
import cn.com.easy.permission.model.ResourceModel;
import cn.com.easy.permission.web.dto.system.ResourceDto;

import com.google.common.collect.Lists;

/**
 * 登录服务类
 * 
 * @author nibili 2015年12月11日下午11:56:08
 * 
 */
@Service
public class UserIndexService {

	/** 权限资源dao */
	@Autowired
	private ResourceDao resourceDao;

	/**
	 * 获取url权限
	 * 
	 * @param request
	 * @author nibili 2015年12月11日
	 */
	public List<String> getPermissions(List<ResourceModel> resourceModels) {
		List<String> urls = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(resourceModels) == true) {
			for (ResourceModel resourceModel : resourceModels) {
				if (StringUtils.isNotBlank(resourceModel.getUrl()) == true) {
					// 添加到权限集合中
					urls.add(resourceModel.getUrl());
				}
			}
		}
		return urls;
	}

	/**
	 * 整理成二级资源 权限树
	 * 
	 * @param resourceModels
	 * @return
	 * @auth nibili 2015年12月12日 上午1:16:41
	 */
	public ResourceDto getResourceDto(List<ResourceModel> resourceModels) {
		// 根
		ResourceDto root = null;
		if (CollectionUtils.isNotEmpty(resourceModels) == true) {
			for (ResourceModel resourceModel : resourceModels) {
				// 找到根节点
				if (resourceModel.getParentId() == null) {
					root = new ResourceDto();
					BeanUtils.copyProperties(resourceModel, root);
					resourceModels.remove(resourceModel);
					break;
				}
			}
			if (root != null) {
				// 查找权限资源树，只显示两级
				// 第一级
				List<ResourceDto> firstLevelNodes = this.getResourceDtoByParentId(root.getId(), resourceModels);
				root.setChildren(firstLevelNodes);
				// 添加第二级
				for (ResourceDto resourceDto : firstLevelNodes) {
					resourceDto.setChildren(this.getResourceDtoByParentId(resourceDto.getId(), resourceModels));
				}
			}
		}
		return root;
	}

	/**
	 * 按父id查找资源权限
	 * 
	 * @param id
	 * @param resourceModels
	 * @return
	 * @auth nibili 2015年12月12日 上午12:15:33
	 */
	private List<ResourceDto> getResourceDtoByParentId(Long id, List<ResourceModel> resourceModels) {
		// 节点集合
		List<ResourceDto> resourceDtoList = Lists.newArrayList();
		for (ResourceModel resourceModel : resourceModels) {
			//
			if (resourceModel.getParentId().longValue() == id.longValue()) {
				// 找到节点
				ResourceDto resourceDtoTemp = new ResourceDto();
				BeanUtils.copyProperties(resourceModel, resourceDtoTemp);
				resourceDtoList.add(resourceDtoTemp);
			}
		}
		return resourceDtoList;
	}
}
